package mid;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * @author WangZhiJian
 * @since 2022/1/16 0016
 */
public class 二叉树根节点到叶子节点的所有路径和 {
    /**
     *运行时间：125ms
     * 超过0.17% 用Java提交的代码
     * 占用内存：15552KB
     * 超过0.82%用Java提交的代码
     * @param root TreeNode类
     * @return int整型
     */
    public int sumNumbers (TreeNode root) {
        // write code here
        List<Integer> res = sumNumbers(root, 0);
       // 结果求和
        return res.stream()
                .mapToInt(Integer::intValue)
                .sum();
    }

    /**
     * 递归左右子树
     * @param root
     * @param nowValue
     * @return
     */
    public List<Integer> sumNumbers (TreeNode root,int nowValue) {
        if(root == null)
            return Collections.emptyList();
        int curVal = nowValue + root.val;
        if(root.left == null && root.right == null)
            return Collections.singletonList(curVal);
        curVal = curVal * 10;
        List<Integer> res1 = sumNumbers(root.left, curVal);
        List<Integer> res2 = sumNumbers(root.right, curVal);
        ArrayList<Integer> res = new ArrayList<>();
        res.addAll(res1);
        res.addAll(res2);
        return res;
    }
}
